from flask import Flask, request, render_template, redirect, url_for
import json
import pymysql
import redis

app = Flask(__name__)


@app.route('/')
def hello():
    return render_template('index.html')


@app.route('/index')
def index():
    conn = pymysql.connect('47.98.50.245', 'zgf', 'ZGFroot1234@', 'scrapy_text', charset='utf8')
    cur = conn.cursor()
    r = redis.Redis(host='47.98.50.245', port=6379, password='root')

    sel_word = request.args.get('in_f')
    print(sel_word)
    print(bytes(sel_word, encoding='utf-8'))
    data_text = r.smembers(bytes(sel_word, encoding='utf-8'))
    print(data_text)
    Text = []
    book_ids = []
    if data_text:
        for i in data_text:
            s = str(i, encoding='utf-8')
            book_ids.append(s)
        sel_books = ','.join(book_ids)
        print(sel_books)
        sel_sql = "SELECT * FROM text_scrapy WHERE id in ({})".format(str(sel_books))
        cur.execute(sel_sql)
        result = cur.fetchall()
        for res in result:
            book_id = res[1]
            book_name = res[2]
            book_auto = res[3]
            book_link = res[4]
            book_url = res[5]
            book_img = res[6]
            data = {
                'book_id': book_id,
                'book_name': book_name,
                'book_auto': book_auto,
                'book_link': book_link,
                'book_url': book_url,
                'book_img': book_img,
            }
            Text.append(data)

    print(Text)
    print(len(Text))
    return json.dumps(Text)


@app.route('/test')
def test():
    return 'ok'


if __name__ == '__main__':
    app.run()
